package com.wkbb.sports.mqtt;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.wkbb.common.handler.JsonUtil;
import com.wkbb.sports.dto.DeviceDto;
import com.wkbb.sports.dto.TrainTsTestDto;
import com.wkbb.sports.mapper.HlifeDeviceMapper;
import com.wkbb.sports.model.HlifeDevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wkbb.common.constants.Constants;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.redis.WxRedisTemplateUtil;
import com.wkbb.sports.feign.BasicFeignService;
import com.wkbb.sports.mapper.HlifeDetectStudentDetailMapper;
import com.wkbb.sports.mapper.HlifeDetectStudentMapper;
import com.wkbb.sports.mapper.HlifeStudentDeviceMapper;
import com.wkbb.sports.model.HlifeDetectStudent;
import com.wkbb.sports.model.HlifeDetectStudentDetail;
import com.wkbb.sports.model.HlifeStudentDevice;
import com.wkbb.sports.utils.SportsUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * 触发event topic 事件
 *
 * @author XJ
 * @date 2021/7/16
 */
@Slf4j
@Component
public class MqJobListener {

    @Autowired
    MqttServer mqttServer;

    @Autowired
    WxRedisTemplateUtil wxRedisTemplateUtil;

    @Autowired
    HlifeDetectStudentDetailMapper hlifeDetectStudentDetailMapper;

    @Autowired
    HlifeDetectStudentMapper hlifeDetectStudentMapper;

    @Autowired
    HlifeStudentDeviceMapper hlifeStudentDeviceMapper;

    @Autowired
    BasicFeignService basicFeignService;

    @Autowired
    HlifeDeviceMapper hlifeDeviceMapper;

    /**
     * 监听topic
     *
     * @param mqttEvent
     */
    @EventListener(condition = "#mqttEvent.topic.equals(T(com.wkbb.sports.mqtt.TopicName).ROLL_CALL_DEFAULT.getValue())")
    public void onEmqttCall(MqttEvent mqttEvent) {
        String message = mqttEvent.getMessage();
//		log.info("接收到消息："+message);

        JSONObject jsonObject = JSON.parseObject(message);
        JSONObject data = jsonObject.getJSONObject("data");
        if (data != null) {
            JSONArray dev_infos = data.getJSONArray("dev_infos");
            if (dev_infos != null) {
                List<String> list = new ArrayList<>();
//                List<TrainTsTestDto> tsTestDtos = new ArrayList<>();
                List<HlifeDetectStudentDetail> studentDetails = new ArrayList<>();
                for (int i = 0; i < dev_infos.size(); i++) {
                    JSONObject item = dev_infos.getJSONObject(i);
                    String name = item.getString("name");
                    if (!"null".equals(name)) {
                        if (name.startsWith("1963YH_")) {
                            String srp_raw = item.getString("srp_raw");
                            if (srp_raw != null && !"".equals(srp_raw)) {
                                String deviceMac = toMac(item.getString("addr"));
                                String olddata = (String) wxRedisTemplateUtil.get(deviceMac);
                                String newdata = srp_raw.substring(34);
                                if (olddata == null || !olddata.equals(newdata)) {
                                    String wd = newdata.substring(2, 4) + newdata.substring(0, 2);
                                    String xl = newdata.substring(4, 6);
//                                    String xy = newdata.substring(6, 8);
                                    String wddata = SportsUtils.covert(wd) / 10 + "." + SportsUtils.covert(wd) % 10;
                                    int xldata = SportsUtils.covert(xl);
//                                    int xydata = SportsUtils.covert(xy);
                                    HlifeDetectStudentDetail hlifeDetectStudentDetail = new HlifeDetectStudentDetail();
                                    hlifeDetectStudentDetail.setTemperature(Double.valueOf(wddata));
                                    hlifeDetectStudentDetail.setHeartRate(xldata);
//                                    hlifeDetectStudentDetail.setBloodOxygen(xydata);
                                    hlifeDetectStudentDetail.setMac(deviceMac);
                                    wxRedisTemplateUtil.set(deviceMac, newdata, 10);

                                    HlifeDetectStudent hlifeDetectStudent = hlifeDetectStudentMapper.findByDeviceMac(deviceMac);
                                    if (hlifeDetectStudent != null) {
                                        hlifeDetectStudentDetail.setDetectStudentId(hlifeDetectStudent.getId());
                                        studentDetails.add(hlifeDetectStudentDetail);
                                        String sendData = "{\"name\":\"" + hlifeDetectStudent.getStudentName() + "\",\"studentNo\":\"" + hlifeDetectStudent.getStudentNo() + "\",\"deviceId\":\"" + hlifeDetectStudent.getDeviceId() + "\",\"heartRate\":" + xldata + ",\"temperature\":" + wddata + "}";
                                        list.add(sendData);
                                    }
                                }
                            }
                        } else if (name.startsWith("CL831") || name.startsWith("CL837")) {
                            String deviceMac = toMac(item.getString("addr"));
                            String olddata = (String) wxRedisTemplateUtil.get(deviceMac);
                            String newdata = item.getString("adv_raw");
                            if (olddata == null || !olddata.equals(newdata)) {
                                String xl = newdata.substring(28, 30);
                                int xldata = Integer.parseInt(xl, 16);
                                HlifeDetectStudentDetail hlifeDetectStudentDetail = new HlifeDetectStudentDetail();
                                hlifeDetectStudentDetail.setHeartRate(xldata);
//                                    hlifeDetectStudentDetail.setBloodOxygen(xydata);
                                hlifeDetectStudentDetail.setMac(deviceMac);
                                wxRedisTemplateUtil.set(deviceMac, newdata, 10);
                                HlifeDetectStudent hlifeDetectStudent = hlifeDetectStudentMapper.findByDeviceMac(deviceMac);
                                if (hlifeDetectStudent != null) {
                                    hlifeDetectStudentDetail.setDetectStudentId(hlifeDetectStudent.getId());
                                    studentDetails.add(hlifeDetectStudentDetail);
                                    String sendData = "{\"name\":\"" + hlifeDetectStudent.getStudentName() + "\",\"studentNo\":\"" + hlifeDetectStudent.getStudentNo() + "\",\"deviceId\":\"" + hlifeDetectStudent.getDeviceId() + "\",\"heartRate\":" + xldata + "}";
                                    list.add(sendData);
                                }
                            }
                        }
                    }
                }
                if (studentDetails.size() > 0) {
                    hlifeDetectStudentDetailMapper.insertBatch(studentDetails);
//                  log.info("网关信息："+ JsonUtil.stringify(tsTestDtos));
                }
                if (list.size() > 0) {
                    log.info("发送消息：" + list);
                    mqttServer.sendToMqtt(Constants.TOPIC, list.toString());
                }
            }
        }
    }

    public String toMac(String device) {
        StringBuilder bf = new StringBuilder();
        int i = 0;
        while (i < 11) {
            String tmp = device.substring(i, i + 2);
            bf.append(tmp);
            if (i != 10) {
                bf.append(":");
            }
            i = i + 2;
        }
        return bf.toString().toUpperCase();
    }

    public String copeDetectData(String device, String newdata) {

        StringBuffer bf = new StringBuffer();
        int i = 0;
        while (i < 11) {
            String tmp = device.substring(i, i + 2);
            bf.append(tmp);
            if (i != 10) {
                bf.append(":");
            }
            i = i + 2;
        }

        String deviceMac = bf.toString();

        HlifeStudentDevice hlifeStudentDevice = hlifeStudentDeviceMapper.selectByParam(deviceMac);

        if (null == hlifeStudentDevice) {
            return null;
        }

        ResultDTO<StudentInfoDto> result = basicFeignService.getStudentByStudentNo(hlifeStudentDevice.getOrgId(), null, hlifeStudentDevice.getStudentId(), null);
        StudentInfoDto studentInfoDto = result.getData();

        HlifeDetectStudent hlifeDetectStudent = hlifeDetectStudentMapper.selecthlifeDetectStudent(hlifeStudentDevice);

        String olddata = (String) wxRedisTemplateUtil.get(hlifeDetectStudent.getDetectId() + deviceMac);

        if (null == olddata || !olddata.equals(newdata)) {
            String wd = newdata.substring(2, 4) + newdata.substring(0, 2);
            String xl = newdata.substring(4, 6);
            String xy = newdata.substring(6, 8);
            String wddata = String.valueOf(SportsUtils.covert(wd) / 10) + "." + String.valueOf(SportsUtils.covert(wd) % 10);
            int xldata = SportsUtils.covert(xl);
            int xydata = SportsUtils.covert(xy);
            HlifeDetectStudentDetail hlifeDetectStudentDetail = new HlifeDetectStudentDetail();
            hlifeDetectStudentDetail.setTemperature(Double.valueOf(wddata));
            hlifeDetectStudentDetail.setHeartRate(xldata);
            hlifeDetectStudentDetail.setBloodOxygen(xydata);
            hlifeDetectStudentDetail.setMac(deviceMac);
            hlifeDetectStudentDetail.setDetectStudentId(hlifeDetectStudent.getId());
            hlifeDetectStudentDetailMapper.insertByParam(hlifeDetectStudentDetail);
            wxRedisTemplateUtil.set(hlifeDetectStudent.getDetectId() + deviceMac, newdata, 10);
            String sendData = "{'name':'" + studentInfoDto.getName() + "','studentNo':'" + studentInfoDto.getStudentNo() + "','deviceId':'" + hlifeStudentDevice.getDeviceName() + "','heartRate':" + xldata + ",'temperature':" + wddata + "}";
            return sendData;
        }
        return null;
    }

    @EventListener(condition = "@ emqttPredicate.test(#mqttEvent)")
    public void onEmqttCallTest(MqttEvent mqttEvent) {
        log.info("测试通过：" + mqttEvent.getMessage());
    }


    public static void main(String[] args) {
//    	  List list = new ArrayList();
//    	  String sendData1 = "{'name':'刘','studentNo':'28','deviceId':'A-28','heartRate':'178','temperature':'37.2'}";
//    	  String sendData2 = "{'name':'刘','studentNo':'28','deviceId':'A-28','heartRate':'178','temperature':'37.2'}";
//    	  list.add(sendData1);
//    	  list.add(sendData2);
//    	  JSONArray json = JSONArray.fromObject(list);
//    	  System.out.print(json.toString());
    }


}

